package com.lft.examsys.controller;

import com.lft.examsys.entity.Kaptcha;
import com.lft.examsys.entity.Paper;
import com.lft.examsys.entity.User;
import com.lft.examsys.model.IModel;
import com.lft.examsys.service.KaptchaService;
import com.lft.examsys.service.PaperService;
import com.lft.examsys.service.UserService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

    @Autowired
    private KaptchaService kaptcha;

    @Autowired
    private UserService userService;

    @Autowired
    private PaperService paperService;

    @GetMapping("/")
    public ModelAndView index(IModel model) {
        //TODO: 首页
        return model.validation("index", () -> {
            if (model.user() != null) {
                List<Paper> papers = paperService.getPapers();
                List<Paper> removes = new ArrayList<>();
                for (Paper paper : papers) {
                    //  本地时间
                    DateTime localTime = new DateTime();
                    //  考试时间
                    DateTime paperTime = new DateTime(paper.getBegin());
                    //  考试时限
                    Integer limitation = paper.getLimitation();
                    //  考试结束时间
                    DateTime endTime = new DateTime(paperTime.plusMinutes(limitation));
                    //  考试时间 > 本地时间  ||  本地时间 > 考试结束时间
                    if (paperTime.isAfter(localTime) || localTime.isAfter(endTime)) {
//                        papers.remove(paper);
                        removes.add(paper);
                    }
                }
                papers.removeAll(removes);
                model.add("papers",papers);
                Map<Object, Object> res = paperService.getPaperCount();
                model.add("itemsCount",res);
            }
        }, model::err);
    }


    @PostMapping("/register")
    public ModelAndView register(IModel model, User user) {
        String nativePassword = user.getPassword();
        return model.validation("/index", () -> {
            DateTime time = new DateTime();
            user.setRegisterTime(time.toDate());
            if (!userService.register(user)) {
                model.failure("用户名已被占用");
            }
            model.add("loginShowed", "loginShowed");
            model.add("username", user.getUsername());
            model.add("password", nativePassword);
        }, (msg) -> {
            model.add("registerShowed", "registerShowed");
            model.err(msg);
        });
    }


    @GetMapping("/kaptcha")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Kaptcha generate = kaptcha.generate();
        HttpSession session = request.getSession();
        session.setAttribute("code", generate.getCode());
        //禁止浏览器缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/gif");

        //将图像输出到Servlet输出流中
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(generate.getImage(), "gif", sos);
        sos.flush();
        sos.close();
    }

    @PostMapping("/codeCheck")
    @ResponseBody
    public Integer codeCheck(HttpSession session, String code) {
        Object rightCode = session.getAttribute("code");
        return rightCode != null && rightCode.toString().equalsIgnoreCase(code) ? 1 : 0;
    }

}
